from django.http import JsonResponse
import json
from ..models import Paper
from django.core.paginator import Paginator
from django.db.models import Q
import django.utils.timezone as timezone


def paper_handle(request):
    if request.method == 'GET':
        request.params = request.GET
    else:
        request.params = json.loads(request.body)
    action = request.params.get('action')

    if action in action_handler_dict_all:  # 无需登录
        return action_handler_dict_all[action](request)
    if not request.user.is_authenticated:  # 其他action都要登录
        return JsonResponse({'ret': 1, 'msg': '未登录'}, json_dumps_params={'ensure_ascii': False})
    if action in action_handler_dict_mg:  # 只有管理员才能操作的action
        if request.user.usertype not in [1, 1000]:
            return JsonResponse({'ret': 1, 'msg': '非管理员'}, json_dumps_params={'ensure_ascii': False})
        return action_handler_dict_mg[action](request)
    if action in action_handler_dict_login:  # 其他登录后的请求
        return action_handler_dict_login[action](request)
    return JsonResponse({'ret': 1, 'msg': 'action参数错误'})

# 所有人可见
def listbypage(request):
    try:
        withoutcontent=request.params.get('withoutcontent')
        if withoutcontent:
            qs = Paper.objects.filter(status=1).values(
            'id', 'pubdate', 'author', 'author__realname', 
            'title', 'thumbupcount', 'status').order_by('-pubdate')
        else:
            qs = Paper.objects.filter(status=1).values(
            'id', 'pubdate', 'author', 'author__realname', 
            'title', 'content', 'thumbupcount', 'status').order_by('-pubdate')

        pagesize = request.params.get('pagesize')
        pagenum = request.params.get('pagenum')
        keywords = request.params.get('keywords')
        if keywords:
            keywords_list = keywords.split()
            query = Q()
            for k in keywords_list:
                query &= Q(title__contains=k)
            qs = qs.filter(query)
        pgnt = Paginator(qs, pagesize)
        page = pgnt.get_page(pagenum)
        items = list(page)
        return JsonResponse(
            {
                'ret': 0, 
                'items': items, 
                'total': pgnt.count,
                'keywords': keywords
            }, json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

# 仅管理员
def listbypage_allstate(request):
    try:
        qs = Paper.objects.values(
        'id', 'pubdate', 'author', 'author__realname', 
        'title', 'content', 'thumbupcount', 'status').order_by('-pubdate')
        pagesize = request.params.get('pagesize')
        pagenum = request.params.get('pagenum')
        keywords = request.params.get('keywords')
        if keywords:
            keywords_list = keywords.split()
            query = Q()
            for k in keywords_list:
                query &= Q(title__contains=k)
            qs = qs.filter(query)
        pgnt = Paginator(qs, pagesize)
        page = pgnt.get_page(pagenum)
        items = list(page)
        return JsonResponse(
            {
                'ret': 0, 
                'items': items, 
                'total': pgnt.count,
                'keywords': keywords
            }, json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

# 学生和老师
def listminebypage(request):
    author = request.user.id
    if request.user.usertype not in [2000, 3000]:
        return JsonResponse(
            {'ret': 1, 'msg': '仅老师和学生展示'}, json_dumps_params={'ensure_ascii': False})
    try:
        qs = Paper.objects.filter(author=author).values(
        'id', 'pubdate', 'author', 'author__realname', 
        'title', 'content', 'thumbupcount', 'status').order_by('-pubdate')
        pagesize = request.params.get('pagesize')
        pagenum = request.params.get('pagenum')
        keywords = request.params.get('keywords')
        if keywords:
            keywords_list = keywords.split()
            query = Q()
            for k in keywords_list:
                query &= Q(title__contains=k)
            qs = qs.filter(query)
        pgnt = Paginator(qs, pagesize)
        page = pgnt.get_page(pagenum)
        items = list(page)
        return JsonResponse(
            {
                'ret': 0, 
                'items': items, 
                'total': pgnt.count,
                'keywords': keywords
            }, json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

# 所有人，但要根据状态进行处理
def getone(request):
    try:
        Paperid = request.params.get('id')
        rec = Paper.objects.filter(id=Paperid).values(
        'id', 'pubdate', 'author', 'author__realname', 
        'title', 'content', 'thumbupcount', 'status')[0]
        if rec.get('status') == 1:
            return JsonResponse(
                {'ret': 0, 'rec': rec,}, json_dumps_params={'ensure_ascii': False})
        if not request.user.is_authenticated:  # 其他action都要登录
            return JsonResponse({'ret': 1, 'msg': '请登录后查看'}, json_dumps_params={'ensure_ascii': False})
        if request.user.usertype in [1, 1000]:
            return JsonResponse(
                {'ret': 0, 'rec': rec,}, json_dumps_params={'ensure_ascii': False})
        if request.user.id == rec['author']:
            return JsonResponse(
                {'ret': 0, 'rec': rec,}, json_dumps_params={'ensure_ascii': False})
        else:
            return JsonResponse({'ret': 1, 'msg': '仅作者可以查看'})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})
            
# 登录用户客户
def addone(request):
    try:
        data = request.params['data']
        data['author'] = request.user
        record = Paper.objects.create(**data)
        return JsonResponse({'ret': 0, 'id': record.id})
    except Exception as e:
        return JsonResponse(
            {'ret': 1, 'msg': str(e)})

# 作者
def modifyone(request):
    try:
        paperid = request.params['id']
        newdata = request.params['newdata']
        record = Paper.objects.filter(id=paperid)
        if request.user.id == record[0].author.id:
            newdata['modidate'] = timezone.now()
            record.update(**newdata)
            return JsonResponse({'ret': 0})
        return JsonResponse({'ret': 1, 'msg': '仅作者可以修改'})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})
# 作者
def holdone(request):
    try:
        paperid = request.params['id']
        paper = Paper.objects.filter(id=paperid)
        if request.user.id == paper[0].author.id:
            paper.update(status=2)
            return JsonResponse({'ret': 0, 'status':f'{paper[0].status}'})
        return JsonResponse({'ret': 1, 'msg': '仅作者可以撤回'})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

# 管理员
def banone(request):
    try:
        paperid = request.params['id']
        paper = Paper.objects.filter(id=paperid)
        paper.update(status=3)
        return JsonResponse({'ret': 0, 'status':f'{paper[0].status}'})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

# 管理员可以对封禁的进行发布，作者可以对撤回的进行发布
def publishone(request):
    try:
        paperid = request.params['id']
        paper = Paper.objects.filter(id=paperid)
        if (request.user.usertype in [1, 1000] and paper[0].status == 3) or (
            paper[0].status == 2 and request.user.id == paper[0].author.id):
            paper.update(status=1)
            return JsonResponse({'ret': 0, 'status':f'{paper[0].status}'})
        return JsonResponse({'ret': 1, 'msg':'权限不足'})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})

# 仅管理员和作者
def deleteone(request):
    try:
        paperid = request.params['id']
        paper = Paper.objects.get(id=paperid)
        if request.user.usertype in [1, 1000] or request.user.id == paper.author_id:
            paper.delete()
            return JsonResponse({'ret': 0})
        return JsonResponse({'ret': 1, 'msg': '权限不足'})
    except Exception as e:
        return JsonResponse({'ret': 1, 'msg': str(e)})


action_handler_dict_all = {
    'listbypage': listbypage,  # all
    'getone': getone,  # all，status
}

action_handler_dict_mg = {
    'listbypage_allstate': listbypage_allstate,  #mg
    'banone': banone,  # mg
}

action_handler_dict_login = {
    'publishone': publishone, # mg
    'listminebypage': listminebypage,  # te st
    'addone': addone,  # all
    'modifyone': modifyone,  # zuozhe
    'holdone': holdone,  # zuozhe
    'deleteone': deleteone,  # mg zuozhe
}